from flask import Flask, request, jsonify, abort
from functools import wraps
from admin_backend import update_user, get_all_users, get_single_user, renew_vip_service, query_user, \
    get_vip_packages, update_vip_package, delete_vip_package, create_admin, delete_admin, get_admins, update_admin, \
    delete_user, query_admin, get_image_by_id, get_images_by_admin
from user_backend import register, login, manage_collection, get_image_details,comment_management, like_management,get_user_likes,admin_delete_comment
from config import Config
from models import db, User, Image, ImageVersion, UserCollect, CollectItem, UserAction, Admin, UserVIP, AdminAction
from datetime import datetime  # 必须导入datetime模块
import oss2
from datetime import datetime
import re
import jwt
from passlib.hash import argon2
from admin_backend import admin_required, get_all_images, upload_image, delete_image, update_image

app = Flask(__name__)
app.config.from_object(Config)
db.init_app(app)  # 初始化数据库连接

auth = oss2.Auth('LTAI5tSSsZreQros8dcchrTe', 'dKoToq83nsV1xMTJN9VwIiryzKOkhg')

# 全局设置响应头允许跨域
@app.after_request
def add_cors_headers(response):
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'GET, POST, PUT, DELETE, OPTIONS'
    response.headers['Access-Control-Allow-Headers'] = 'Content-Type, X-User-ID'
    return response

# 北京region的正确配置（根据控制台显示的实际region配置）
endpoint = "https://oss-cn-beijing.aliyuncs.com"
bucketName = "mjseed-code-image"
bucket = oss2.Bucket(auth, endpoint, bucketName)


# ----------------- 路由定义 -----------------
#WPJ
# 用户认证
@app.route('/register', methods=['POST'])
def register_route():
    """用户注册路由"""
    return register()


@app.route('/login', methods=['POST'])
def login_route():
    """用户登录路由"""
    return login()

# 图片相关
@app.route('/images/<string:image_id>', methods=['GET'])
def get_image_details_route(image_id):
    """图片详情路由"""
    return get_image_details(image_id)

# 收藏管理
@app.route('/collect', methods=['POST', 'DELETE', 'GET', 'PATCH'])

def manage_collection_route():
    """收藏管理路由"""
    return manage_collection()

# 评论管理
@app.route('/comment', methods=['POST', 'GET', 'DELETE'])

def comment_management_route():
    """用户评论管理路由"""
    return comment_management()

# 管理员评论路由 
@app.route('/admin/comments/<int:action_id>', methods=['DELETE'])
@admin_required  # 需要管理员权限验证装饰器
def admin_delete_comment_route(action_id):
    """管理员删除评论路由"""
    return admin_delete_comment(action_id)

# 点赞管理
@app.route('/like', methods=['POST', 'DELETE'])

def like_management_route():
    """点赞管理路由"""
    return like_management()

@app.route('/likes', methods=['GET'])

def get_user_likes_route():
    """获取用户点赞列表路由"""
    return get_user_likes()



# 管理员相关的路由  LJH

# 查看所有照片信息
@app.route('/admin/images', methods=['GET'])
@admin_required
def get_all_images_route():
    return get_all_images()


#查询全部oss照片的返回都是文件名
# @app.route('/admin/images/list', methods=['GET'])
# @admin_required
# def list_oss_files():
#     try:
#         result = bucket.list_objects()
#         files = [item.key for item in result.object_list]
#         return jsonify({'files': files}), 200
#     except Exception as e:
#         return jsonify({'error': str(e)}), 500


#   上传照片
@app.route('/admin/images/upload', methods=['POST'])
@admin_required
def upload_image_route():
    return upload_image()

#   删除照片
@app.route('/admin/images/<image_id>', methods=['DELETE'])
@admin_required
def delete_image_route(image_id):
    return delete_image(image_id)

#   更新照片
@app.route('/admin/images/<image_id>', methods=['PUT'])
@admin_required
def update_image_route(image_id):
    return update_image(image_id)

#   查询照片（id）
@app.route('/image/<int:image_id>', methods=['GET'])
def get_image(image_id):
    return get_image_by_id(image_id)

#   管理员查看自己发布的照片
@app.route('/admin/images/<int:admin_id>', methods=['GET'])
@admin_required
def handle_admin_images(admin_id):
    return get_images_by_admin(admin_id)




#   删除单个用户信息
app.add_url_rule('/admin/users/<int:user_id>', view_func=delete_user, methods=['DELETE'])

#   修改单个用户信息
app.add_url_rule('/admin/users/<int:user_id>', view_func=update_user, methods=['PUT'])

#   获取全部用户信息
app.add_url_rule('/admin/users', view_func=get_all_users, methods=['GET'])

#   查看单个用户信息
app.add_url_rule('/admin/users/<int:user_id>', view_func=get_single_user, methods=['GET'])

#   可以通过user_id、user_name、phone_number其中一个查询到单一用户信息
app.add_url_rule('/admin/query_user', view_func=query_user, methods=['GET'])

#   VIP充值续费
@app.route('/vip/renew', methods=['POST'])
def renew_vip():
    """
    VIP续费接口（支持套餐类型）
    Request JSON示例:
    {
        "user_id": 123,
        "payment_id": "PAY123",
        "package_type": "monthly",  # 新增参数
        "use_discount": false       # 是否使用折扣（预留字段）
    }
    """
    data = request.json
    required_fields = ['user_id', 'payment_id', 'package_type']
    if not all(field in data for field in required_fields):
        return jsonify({'error': '缺少必要参数'}), 400

    # 调用服务层
    result, status_code = renew_vip_service(
        user_id=data['user_id'],
        payment_id=data['payment_id'],
        package_type=data['package_type'],
        use_discount=data.get('use_discount', False)  # 预留折扣字段
    )
    return jsonify(result), status_code

# VIP套餐管理
app.add_url_rule('/admin/vip-packages', view_func=get_vip_packages, methods=['GET'])
app.add_url_rule('/admin/vip-packages', view_func=update_vip_package, methods=['POST', 'PUT'])
app.add_url_rule('/admin/vip-packages/<int:package_id>', view_func=delete_vip_package, methods=['DELETE'])


#对管理员的增删改查
app.add_url_rule('/admin/admins', view_func=create_admin, methods=['POST'])
app.add_url_rule('/admin/admins/<admin_id>', view_func=delete_admin, methods=['DELETE'])
app.add_url_rule('/admin/admins/<admin_id>', view_func=update_admin, methods=['PUT'])
app.add_url_rule('/admin/admins', view_func=get_admins, methods=['GET'])
app.add_url_rule('/admin/query', view_func=query_admin, methods=['GET'])





@app.route('/upload', methods=['POST'])
def upload_file():
    # 获取前端传来的文件
    file = request.files['file']
    if file:
        # 直接将文件上传到 OSS
        bucket.put_object(file.filename, file)
        return '上传成功'
    else:
        return '上传失败'

















if __name__ == '__main__':
    with app.app_context():
        db.create_all()  # 根据模型创建新表
    app.run(host='0.0.0.0', port=5000, debug=True)